import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:raze/artifacts/upload_emissary_dialog.dart';
import 'package:raze/potions/raze_constant.dart';
import 'package:raze/potions/spatial_alchemy.dart';
import 'package:raze/realms/navigation_one_realms/home_realms.dart';
import 'package:raze/realms/navigation_two_realms/community_realms.dart';
import 'package:raze/realms/navigation_three_realms/diary_realms.dart';
import 'package:raze/realms/navigation_four_realms/my_home_realms.dart';

/// 主页面
/// 包含底部导航栏和页面切换功能
class MainRealms extends StatefulWidget {
  const MainRealms({super.key});

  @override
  State<MainRealms> createState() => _MainRealmsState();
}

class _MainRealmsState extends State<MainRealms>
    with SingleTickerProviderStateMixin {
  int _currentIndex = 0;
  late PageController _pageController;
  late AnimationController _animationController;

  final List<Widget> _pages = [
    HomeRealms(),
    const CommunityRealms(),
    const DiaryRealms(),
    const MyHomeRealms(),
  ];

  @override
  void initState() {
    super.initState();
    _pageController = PageController(initialPage: _currentIndex);
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 300),
    );
  }

  @override
  void dispose() {
    _pageController.dispose();
    _animationController.dispose();
    super.dispose();
  }

  /// 切换页面
  void _switchPage(int index) {
    if (index == 2) {
      // 中间的上传按钮，显示上传弹窗
      UploadEmissaryDialog.revealUploadEmissary(
        onCommunityTap: () {
          // 跳转到发布页面（发布社区）
          Get.toNamed('/publish', parameters: {'type': 'community'});
        },
        onDiaryTap: () {
          // 跳转到发布页面（发布日志）
          Get.toNamed('/publish', parameters: {'type': 'diary'});
        },
      );
      return;
    }

    // 导航索引映射：0->0, 1->0, 2跳过, 3->1, 4->2, 需要调整为：0,1,2,3 -> 0,1,3,4
    // 但实际上底部导航只有4个按钮+中间上传，所以索引应该是：0,1,跳过,3,4 -> 对应页面索引：0,1,2,3
    int pageIndex = index > 2 ? index - 1 : index;

    if (_currentIndex != pageIndex) {
      setState(() {
        _currentIndex = pageIndex;
      });
      _pageController.animateToPage(
        pageIndex,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
      _animationController.forward(from: 0.0);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: RazeConstants.background,
      body: Stack(
        children: [
          // 页面内容
          PageView(
            controller: _pageController,
            physics: const NeverScrollableScrollPhysics(),
            children: _pages,
          ),

          // 底部导航栏（使用 Positioned 固定在底部）
          Positioned(
            bottom: 0.h,
            left: 0,
            right: 0,
            child: _buildBottomNavigationBar(),
          ),
        ],
      ),
    );
  }

  /// 构建底部导航栏
  Widget _buildBottomNavigationBar() {
    return LayoutBuilder(
      builder: (context, constraints) {
        final screenWidth = constraints.maxWidth;
        final navBarWidth = screenWidth - 32.w;
        final navBarHeight = navBarWidth * (68 / 343);
        final bottomPadding = MediaQuery.of(context).padding.bottom;

        return Container(
          padding: EdgeInsets.only(top: 16.h, bottom: bottomPadding),
          child: Container(
            width: navBarWidth,
            height: navBarHeight,
            margin: EdgeInsets.symmetric(horizontal: 16.w),
            decoration: BoxDecoration(
              color: RazeConstants.yellow,
              borderRadius: BorderRadius.circular(20.r),
              boxShadow: [
                BoxShadow(
                  color: RazeConstants.black.withOpacity(0.1),
                  blurRadius: 10,
                  offset: const Offset(0, 4),
                ),
              ],
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                _buildNavItem(
                  index: 0,
                  iconPath: 'assets/images/shouye.png',
                  isSelected: _currentIndex == 0,
                ),
                _buildNavItem(
                  index: 1,
                  iconPath: 'assets/images/shequ.png',
                  isSelected: _currentIndex == 1,
                ),
                _buildUploadButton(),
                _buildNavItem(
                  index: 3,
                  iconPath: 'assets/images/rizhi.png',
                  isSelected: _currentIndex == 2,
                ),
                _buildNavItem(
                  index: 4,
                  iconPath: 'assets/images/wode.png',
                  isSelected: _currentIndex == 3,
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  /// 构建导航项
  Widget _buildNavItem({
    required int index,
    required String iconPath,
    required bool isSelected,
  }) {
    return GestureDetector(
      onTap: () => _switchPage(index),
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
        width: isSelected ? 50.w : 40.w,
        height: isSelected ? 50.w : 40.w,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: isSelected ? Color(0xFFF3D185) : Colors.transparent,
          boxShadow:
              isSelected
                  ? [
                    BoxShadow(
                      color: Color(0x30000000),
                      blurRadius: 2,
                      offset: Offset(0, 4),
                      spreadRadius: 0,
                    ),
                  ]
                  : null,
        ),
        child: Center(
          child: AnimatedScale(
            scale: isSelected ? 1.1 : 1.0,
            duration: const Duration(milliseconds: 300),
            curve: Curves.easeInOut,
            child: Image.asset(
              iconPath,
              width: isSelected ? 24.w : 22.w,
              height: isSelected ? 24.w : 22.w,
              fit: BoxFit.contain,
              color: isSelected ? null : RazeConstants.white,
              colorBlendMode: isSelected ? BlendMode.dst : BlendMode.srcIn,
            ),
          ),
        ),
      ),
    );
  }

  /// 构建上传按钮
  Widget _buildUploadButton() {
    return Container(
      width: 48.w,
      height: 39.w,
      decoration: BoxDecoration(
        color: RazeConstants.black,
        borderRadius: BorderRadius.circular(12.r),
        boxShadow: [
          BoxShadow(
            color: RazeConstants.black.withOpacity(0.3),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Icon(Icons.add_rounded, color: RazeConstants.white, size: 32.sp),
    ).withTouchResonance(onTap: () => _switchPage(2));
  }
}
